package server

import (
	"context"
	v1 "traceid-test/api/helloworld/v1"
	"traceid-test/internal/conf"
	"traceid-test/internal/service"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/transport"
	"github.com/go-kratos/kratos/v2/transport/http"
	"go.opentelemetry.io/otel/trace"
)

// 自定义中间件返回trace-id
func TraceHeader() middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (interface{}, error) {
			if tr, ok := transport.FromServerContext(ctx); ok {
				if ht, ok := tr.(http.Transporter); ok { //http
					traceId := trace.SpanFromContext(ctx).SpanContext().TraceID().String()
					ht.ReplyHeader().Set("trace-id", traceId)
				}
			}
			return handler(ctx, req)
		}
	}
}

// NewHTTPServer new an HTTP server.
func NewHTTPServer(c *conf.Server, greeter *service.GreeterService, logger log.Logger, tp trace.TracerProvider) *http.Server {

	var opts = []http.ServerOption{
		http.Middleware(
			tracing.Server(
				tracing.WithTracerProvider(tp), //如果有地方全局设置了，这里就不需要了
			),
			// logging.Server(logger),
			recovery.Recovery(),
			TraceHeader(),
		),
	}
	if c.Http.Network != "" {
		opts = append(opts, http.Network(c.Http.Network))
	}
	if c.Http.Addr != "" {
		opts = append(opts, http.Address(c.Http.Addr))
	}
	if c.Http.Timeout != nil {
		opts = append(opts, http.Timeout(c.Http.Timeout.AsDuration()))
	}
	srv := http.NewServer(opts...)
	v1.RegisterGreeterHTTPServer(srv, greeter)
	return srv
}
